/**
地址组件

属性：
  value:{code:String,addre:String}  其中code需要完整代码，例如：行政区划：150302
  size:String 组件默认大小（'medium','small','mini'）
  width:String 组件的宽度,默认100%
*/
<template>
  <div>
    <el-cascader
      :size="size"
      :style="{width}"
      placeholder="请搜索或选择"
      :props="{ expandTrigger: 'hover' }"
      filterable
      clearable
      :options="options"
      v-model="select"
      @change="input"
    />
    <el-input :style="{width}" :size="size" v-model="text" @change="input" />
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type:Object,
      validator:function(value){
        return value.hasOwnProperty('code') && value.hasOwnProperty('addre')
      },
      default:{code:'',addre:''}
    },
    filter: Function,
    size:{
      type:String,
      validator: function(value) {
        return ['medium','small','mini'].findIndex(item=>item==value)>=0;
      },
      default:'medium'
    },
    width:{type:String,default:'100%'},
  },
  
  data() {
    return {
      select: [],
      text: "",
      options: [],
      rule:""
    };
  },
  methods: {
    input(value) {
      this.$emit("input", { code: this.select.join(""), addre: this.text });
    },
    splitCode(val){
      if (typeof val != 'undefined' && typeof this.role != 'undefined'){
        const len = parseInt(this.role.split(':')[0])
        const arr = this.role.split(':')[1].split('|')
        //变更级联选择器的传入值为el-cascader的标准格式
        let list = []
        let start = 0
        let end = len
        for (let i=0;i<arr.length;i++){
          if (i>0){
            start += parseInt(arr[i-1])
          }else{
            start = 0
          }
          end = start + parseInt(arr[i])
          list.push(val.substring(start,end))
        }
        return list
      }
    }
  },
  async mounted() {
    //如果有过滤需求，则由filter这个方法来提供数据,TODO: 需要完善过滤方法
    if (typeof this.filter == 'undefined'){
      return this.filter()
    }else{
      const data = await this.$dict.getTree('行政区划')
      this.options = data.tree
      this.role = data.role
    }
    if (typeof this.value != "undefined") {
      this.select = this.splitCode(this.value.code)
      this.text = this.value.addre
    }
  },
};
</script>
